<script setup>
import { useUserInfoStore } from '@/stores/userInfo.js';
import { useRoute,useRouter } from 'vue-router';
import { setToken,removeToken } from '@/utils/auth'
import { ref,reactive,onMounted } from 'vue';
import getRules from "@/validUtils";
import { useTagsStore } from '@/stores/tag.js'
import { ElMessage } from 'element-plus'
import { useMenuStore } from '@/stores/menu.js'
import { injoinLogin,getUserInfo,getImgCode,getFailCount } from '@/api/Login/index.js'
import { getDistInfo,getArea,getDistInfos,getAreaRoles} from '@/api/Other/index.js'
import { useDistInfoStore } from '@/stores/dict.js'
import {useAreaInfoStore} from '@/stores/area.js'
import {getRouters} from "@/api/System"
import {
  buildTrees,
} from "@/utils/common.js";
// 引入md5加密
import md5 from 'md5'
let distInfoStore = useDistInfoStore();
let areaInfoStore = useAreaInfoStore()
let tagsStore  = useTagsStore();
let menuStore = useMenuStore();
let type = ref("login");
let loading = ref(false);
let loginform = ref(null);
let passwordType = ref(false);
let route = useRoute();
let router = useRouter();

let login = reactive({
  account: "admin",
  password: "test",
  code: "",
});
const loginNumber = ref(0);

function handleShowPassword(flag) {
    passwordType.value = flag;
};
const _login = async ()=>{


  loading.value = true;;
  let params = {
      username:login.account,
      password:md5(login.password),
      grant_type:"password"
  }
  if((login.code??'')!==''){
    params.code = login.code;
  }
  try{

    let result = await injoinLogin(params);
    setToken(result.access_token);

    let menu = await getRouters()
    const menus = buildTrees(menu.map(v=>({
      ...v,
      parentId: v.pid,
    })))
    menuStore.setRouters(menus)
    const cloudUserInfo = await getUserInfo();

    let UserInfo =  useUserInfoStore();
    UserInfo.setUserInfo(cloudUserInfo)
    
    let distInfo = await getDistInfo();
    distInfoStore.setDistInfo(distInfo);

    // 获取地区信息以及地区所映射的门店分组
    let areaInfo = await getArea()
    areaInfoStore.setAreaInfo(areaInfo)


    // 获取加权限的数据字典
    let distInfoRoles = await getDistInfos();
    distInfoStore.setDistInfos(distInfoRoles);


    // 获取带权限的地区及地区所映射的门店分组
    let areaRolesInfo = await getAreaRoles()
    areaInfoStore.setAreaRolesInfo(areaRolesInfo)

    tagsStore.setTags({
      path: "/hello",
      name: "Hello",
      label: "首页",
      component: "Home/hello.vue",
      hidden: true,
      fullPath: "/hello"
    })
    setTimeout(()=>{
      loading.value = false;;
      router.push('/');
    },300)

  }catch(e){
    removeToken();
    _getFailCount();
    loading.value = false;;
  }finally{

  }
}

const toRouterTree = ()=>{

}

const _getFailCount = async ()=>{
  if((login.account??'') ==='')return;
  loginNumber.value = await getFailCount({username:login.account,clientId:"system-client"});
  if(loginNumber.value >= 3){          
    _getImgCode();
  }
};
const handleSubmit = () => {
  _login();
}
const imgSrc = ref(null);

const _getImgCode = async ()=>{
  imgSrc.value = await getImgCode({username:login.account,clientId:"system-client"});
}

const maskerFlag = ref(true);
onMounted(() => {
  $(".door .nr").animate({ opacity: 0 }, 1000, () => {
    maskerFlag.value = false;
  });
});
const showImg = new URL('@/assets/images/login/show.png',import.meta.url);
const hideImg = new URL('@/assets/images/login/hide.png',import.meta.url);
</script>
<template>
    <div class="door" v-if="maskerFlag">
      <div class="nr"></div>
    </div>
    <div class="login">

        <div class="copyright">
          Copyright ©2022 九为（浙江）网络科技有限公司版权所有     备案号：<a href="https://beian.miit.gov.cn" target="_blank">浙ICP备20015044号</a>
        </div>
        <div class="login-frame">
          <div class="left-login-body">
            <div class="p1">
              九养云
            </div>
            <div class="p2">
              九养云管理平台
            </div>
            <div class="h-line"></div>
            <div class="p3">
              康复连锁数字化经营管理专家
            </div>
          </div>
          <div class="right-login-body">
            <div class="p1">
              登录
            </div>
            <el-form :model="login">
              <div class="login-item" style="margin-top:32px">
                <div class="label-name">
                  账号
                </div>
                <div class="login-input">
                  
                  <el-input
                        auto-complete="jyy_username"
                        name="jyy_username"
                        type="text"
                        placeholder="请输入"
                        v-model="login.account"
                        @keydown.enter="handleSubmit(login)"
                        @blur="_getFailCount"
                        id="username"
                    >
                    <template #suffix>
                        <div
                            v-show="login.account"
                            class="login-suffix"
                            style="position:relative;"
                        >
                          <img
                              src="@/assets/images/login-close.png"
                              alt=""
                              style="margin-right:6px;width:18px;height:18px;cursor:pointer"
                              @click="login.account = ''"
                          />
                        </div>
                    </template> 
                  </el-input>
                </div>
              </div>
              <div class="login-item" style="margin-top:16px">
                <div class="label-name">
                  密码
                </div>
                <div class="login-input">
                  <el-input
                      auto-complete="jyy_password"
                      name="jyy_password"
                      v-model.trim="login.password"
                      :type="passwordType ? 'text' : 'password'"
                      oncopy="return false"
                      onpaste="return false"
                      oncut="return false"
                      oncontextmenu="return false"
                      placeholder="请输入"
                      @keydown.enter="handleSubmit(login)"
                      
                    >
                    <template #suffix>
                      <div
                          v-show="login.password"
                          class="login-suffix"
                          
                          style="position:relative;width: 48px;"
                      >
                        <img
                            src="@/assets/images/login-close.png"
                            alt=""
                            style="margin-right:6px;width:18px;height:18px;cursor:pointer"
                            @click="login.password = ''"
                        />
                        <img
                            :src="passwordType?showImg:hideImg"
                            alt=""
                            @click="handleShowPassword(false)"
                            style="width:16px;height:16px;cursor:pointer"
                            @mousedown="passwordType = true"
                            @mouseup="passwordType = false"
                        />

                      </div>
                    </template>   
                  </el-input>
                </div>
              </div>
              <div class="login-item" style="margin-top:16px" v-if="loginNumber>=3">
                <div class="label-name">
                  验证码
                </div>
                <div class="login-input">
                  <el-input
                        type="text"
                        placeholder="请输入"
                        v-model="login.code"
                        @keydown.enter="handleSubmit(login)"
                        style="width: 184px;"
                    >
                    <template #suffix>
                        <div
                            v-show="login.code"
                            class="login-suffix"
                            style="position:relative;"
                        >
                          <img
                              src="@/assets/images/login-close.png"
                              alt=""
                              style="margin-right:6px;width:18px;height:18px;cursor:pointer"
                              @click="login.code = ''"
                          />
                        </div>
                    </template> 
                  </el-input>
                  <div class="v-code-img">
                    <img :src="imgSrc" alt="">
                    <div class="text-area" @click="_getImgCode()">
                      看不清
                      换一张
                    </div>
                  </div>
                </div>
              </div>
            </el-form>
            <el-button
                type="primary"
                @click="handleSubmit(login)"
                class="login-btn"
                :disabled="loginNumber>=3?login.account && login.password && login.code?false:true:login.account && login.password?false:true"
                :style="{'margin-top':loginNumber>=3?'32px':'48px'}"
                :loading="loading"
            >
              登录
            </el-button>
          </div>
        </div>

    </div>
</template>
<style lang="less" scoped>
a {
  text-decoration: none;
}
.login {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  background: url("@/assets/images/login-bg-3.png");
  background-size: 100% 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  .copyright {
    width: 100%;
    position: absolute;
    left: 0;
    bottom: 24px;
    font-size: 14px;
    text-align: center;
    color: #666;

    a {
      color: #666;
    }
  }

  .login-frame {
    width: 790px;
    height: 476px;
    position: relative;
    .right-login-body {
      width: 476px;
      height: 476px;
      position: absolute;
      right: 0;
      top: 0;
      background: url("@/assets/images/login-bg-1.png");
      background-size: 100% 100%;
      z-index: 2;
      box-sizing: border-box;
      padding: 0 68px;
      padding-top: 48px;
      box-shadow: 0 0 18px rgba(12, 38, 140, 0.06);
      .login-btn {
        width: 100%;
        height: 40px;
        background: #3480ff;
        font-size: 16px;
      }
      :deep(.el-button.is-disabled) {
        opacity: 0.5;
      }
      .login-item {
        width: 100%;
        .label-name {
          width: 100%;
          color: #222222;
          font-size: 14px;
          font-weight: 400;
          line-height: 14px;
        }
        .login-input {
          width: 100%;
          margin-top: 16px;
          display: flex;
          justify-content: space-between;

          .v-code-img {
            height: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;
            img {
              width: 90px;
              height: 40px;
              margin-right: 12px;
            }
            .text-area {
              width: 42px;
              line-height: 17px;
              font-size: 14px;
              color: #3480ff;
              cursor: pointer;
            }
          }
          :deep(.el-input) {
            border-radius: 40px;
            border: 2px solid #000000;
            background: rgba(0, 0, 0, 0);
            .login-suffix {
              height: 100%;
              display: flex;
              align-items: center;
              width: 18px;
            }

            .el-input__wrapper {
              background: rgba(0, 0, 0, 0);
              border: 0;
              box-shadow: none;

              .el-input__inner {
                font-size: 16px;
                height: 34px;

                color: #000000;
                &::placeholder {
                  color: #999999;
                }
              }
            }
          }
        }
      }
      .p1 {
        color: #000000;
        font-size: 28px;
        width: 100%;
        font-weight: bold;
        line-height: 28px;
      }
    }
    .left-login-body {
      width: 380px;
      height: 420px;
      position: absolute;
      left: 0;
      top: calc((476px - 420px) / 2);
      background: url("@/assets/images/login-bg-2.png");
      background-size: 100% 100%;
      box-sizing: border-box;
      padding: 0 24px;
      padding-top: 97px;
      .p1 {
        font-weight: bold;
        width: 100%;
        font-size: 24px;
        color: #fff;
      }
      .p2 {
        font-weight: bold;
        width: 100%;
        font-size: 16px;
        color: #fff;
        margin-top: 15px;
      }
      .h-line {
        width: 40px;
        height: 4px;
        border-radius: 2px;
        background: #fff;
        margin-top: 15px;
      }
      .p3 {
        font-weight: 400;
        width: 100%;
        font-size: 16px;
        color: #fff;
        margin-top: 15px;
      }
    }
  }
}
</style>
<style lang="less" scoped>
.door {
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: fixed;
  z-index: 100;
  .nr {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 100%;
    height: 100%;
    opacity: 1;
    transform: translate(-50%, -50%);
    background: rgba(255, 255, 255, 1);
  }
}
</style>
